/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1/commercial
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may use this file in compliance with the License.
 * Alternatively, if you can't copy with the License, namely if you do not
 * want to provide source code of your modifications to this file, you may
 * negotiate a commercial licence with the initial developer.
 * You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is COID.
 *
 * The Initial Developer of the Original Code is
 * PosAm.
 * Portions created by the Initial Developer are Copyright (C) 2003
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 * Brano Kemen
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "treemgr.h"
#include "threadmgr.h"
#include "server.h"

//#include "pthread.h"

namespace coid {

////////////////////////////////////////////////////////////////////////////////
void CoidNode::request_detach()
{
    SRVROOTA._objmgr.request_detach(_id,false);
}

////////////////////////////////////////////////////////////////////////////////
opcd TreeMgr::request_detach( LNID obj, bool children_only )
{
    dynarray<t_tree::ObjList> dlx;
    REF id;

    //get detach list and signal the objects
    GUARDME;

    if( !_tree.get_node( obj, id ) )
        return ersOUT_OF_RANGE "invalid index";

	if( id->_node->is_exit_signalled() )
		return 0;

    _tree.get_detach_list( id, dlx );
    if( children_only )
        dlx.resize(-1);

    charstr dbglst;

    for( uint i=0; i<dlx.size(); ++i )
    {
        DASSERT( _tree.node_exists(dlx[i].id) );

		if( !dlx[i].node->is_exit_signalled() )
		{
            *_deadlist.add() = dlx[i].id;

            dbglst << dlx[i].id.get_node_id() << "\t" << dlx[i].node->class_name() << " marking for deletion\n";

            dlx[i].node->set_can_attach(false);
            dlx[i].node->signal_exit();
	        dlx[i].node->on_exit_signalled();   //non-locked method

            if( dlx[i].nc.is_of_type( ServiceCoid::GET_INTERFACE() ) )
                _svcreg.del( ((ServiceCoid*)dlx[i].node)->class_name() );

            if( dlx[i].nc.is_of_type( ServiceInstanceCoid::GET_INTERFACE() )
                &&  (((ServiceInstanceCoid&)*id)._flags & ServiceInstanceCoid::fAUTOINSTANCE) )
                _svcireg.del( ((ServiceInstanceCoid*)dlx[i].node)->class_name() );
        }
    }

    SRVROOTA.post_server_msg(LOGMSG::TYPE_TRACE,2) << "detach request:\n" << dbglst << EOM;
    return 0;
}

////////////////////////////////////////////////////////////////////////////////
uints TreeMgr::detach_dead()
{
    GUARDME;

    {for( uint i=0; i<_deadlist.size(); ++i )
    {
        if( _deadlist[i] == UMAX32 )  continue;
        REF nd;
        if( !_tree.get_node( _deadlist[i], nd ) ) {
            _deadlist.del(i--);
            continue;
        }

        if( nd->_node->threads_running() )
            continue;

        if( nd.has_children() || nd.has_dependants() )
            continue;
        

        OPCD_CATCH( nd->_node->dpx_destroy() );
        _tree.detach_single( _deadlist[i] );

        _deadlist.del(i--);
    }}

    return _deadlist.size();
}

////////////////////////////////////////////////////////////////////////////////
opcd TreeMgr::get_tree_info( dynarray<tree_info>& out, uints* ref ) const
{
    GUARDME;

    uint count = _tree.count();
    out.reserve( count, false );

    for( uint i=0; i<count; ++i )
    {
        REF id;
        if( !_tree.get_node(i, id) )  continue;
        tree_info* ti = out.add();

        try {
            ti->id = i;
            ti->pid = (LNID)id->_superior;
            ti->code = id->_node->class_name();
            ti->name = id->_node->_name;

            const dynarray<thread>& thr = id->_node->_thr_own;
            uints nt = thr.size();
            for( uints j=0; j<nt; ++j )
            {
                tree_info* tti = out.add();
                tti->id = tree_info::CHANGE_SET_THREAD | i;
                tti->pid = thr[j];
                tti->code = "thread";

                if( 0 != SRVROOTA._thrmgr.get_thread_name( tti->pid, tti->name ) )
                        tti->name = "??UNNAMED THREAD??";
            }
        }
        catch(...)
        {
            binstream& log = SRVROOTA.post_server_msg(LOGMSG::TYPE_CRIT,0);
            log << "exception occured accessing object " << i << " (TreeMgr::get_tree_info)" << EOM;
            out.resize(-1);
        }
    }

    *ref = _change_base + _change_list.size();
    return 0;
}

////////////////////////////////////////////////////////////////////////////////
opcd TreeMgr::get_tree_info_changes( uints& ref, dynarray<tree_info>& out ) const
{
    GUARDME;

    if( ref < _change_base )
        return ersUNAVAILABLE "history deleted";

    if( ref >= _change_base + _change_list.size() )
        return 0;

    uints k = ref - _change_base;
    out.reserve( _change_list.size() - k, false );

    //list for objects set and deleted in this cycle
    //dynarray<uint> tempdel;

    for( ; k < _change_list.size(); ++k )
    {
        tree_info* ti = out.add();
		ti->id = _change_list[k];

        try {

            switch( ti->id & tree_info::xCHANGE_TYPE )
            {
            case tree_info::CHANGE_DEL_OBJECT:
                {
    /*                //remove deletes that apply to new adds
                    if( ti->id == tree_info::CHANGE_DEL_OBJECT  &&  tempdel.size() > 0 )
                    {
                        int p = tempdel.contains(ti->id);
                        if( p>0 )
                        {
                            tempdel.del(p);
                            out.need( out.size() - 1 );
                            continue;
                        }
                    }
    */
    			    ti->pid = UMAX32;
                }
                break;

            case tree_info::CHANGE_DEL_THREAD:
                ti->pid = _change_list[++k];
                break;

            case tree_info::CHANGE_SET_THREAD:
                {
                    ti->pid = _change_list[++k];
                    ti->code = "thread";

                    if( 0 != SRVROOTA._thrmgr.get_thread_name( ti->pid, ti->name ) )
                        ti->name = "??UNNAMED THREAD??";
                } break;

            case tree_info::CHANGE_SET_OBJECT:
                {
                    REF id;
                    if( !_tree.get_node( ti->id & tree_info::xCHANGE_ID, id) )
                    {
                        //there's a delete queued
                        //uint delid = ti->id | tree_info::fOP_DELETE;
                        //*tempdel.add() = delid;
                        out.need( out.size() - 1 );
                        continue;
                    }

                    ti->pid = (LNID) id->_superior;
                    ti->code = id->_node->class_name();
                    ti->name = id->_node->_name;
                }
            }
        }
        catch(...)
        {
            binstream& log = SRVROOTA.post_server_msg(LOGMSG::TYPE_CRIT,0);
            log << "exception occured accessing object " << ti->id << " (TreeMgr::get_tree_info_changes)" << EOM;
            out.resize(-1);
        }
    }

    ref = _change_base + _change_list.size();
    return 0;
}

////////////////////////////////////////////////////////////////////////////////
opcd CoidNode::threads_free()
{
    thread_t self = thread::self();

    {for( uint i=0; i<_thr_own.size(); )
    {
        if( _thr_own[i] != self  &&  !_thr_own[i].is_invalid() )
        {
            thread_free( _thr_own[i] );
            _thr_own[i] = thread::invalid();
        }
        else
            ++i;
    }}

    //_thr_own.discard();

    {for( uint i=0; i<_thr_using.size(); )
    {
        if( _thr_using[i] != self  &&  !_thr_using[i].is_invalid()  )
        {
            thread_free( _thr_using[i] );
            _thr_using[i] = thread::invalid();
        }
        else
            ++i;
    }}

    //_thr_using.discard();

    return 0;
}

////////////////////////////////////////////////////////////////////////////////
#ifdef SYSTYPE_MSVC
#include <windows.h>
//void* LoadLibrary( const char* fname );
//void* GetProcAddress( void* hmodule, const char* procname );

typedef unsigned long (__stdcall *t_AlertThread) (void* thread);
#endif


////////////////////////////////////////////////////////////////////////////////
void CoidNode::thread_free( thread_t tid )
{
#ifdef SYSTYPE_WIN
    static t_AlertThread alert_thread=0;
    if(!alert_thread)
    {
        void* h = LoadLibrary ("ntdll.dll");
        alert_thread = (t_AlertThread) GetProcAddress( (HINSTANCE)h, "NtAlertThread" );
    }
#endif

    uint oid = UMAX32;
    ThreadMgr::get_thread_oid( tid, oid );

    //const thread_info* ti = SRVROOTA._thrmgr.get(tid);
    
    binstream& log = SRVROOTA.post_server_msg(LOGMSG::TYPE_TRACE,2);

    if(oid != UMAX32)
        log << "canceling thread of object (oid: " << oid << " tid: " << tid << ")" << EOM;
    else
        log << "canceling thread of object (oid: " << "unknown, tid: " << tid << ")" << EOM;

    thread t(tid);
    if( 0 != t.cancel() )
		return;	/// error (thread probably does not exist)

#ifdef SYSTYPE_WIN
    //wake up win blocked threads
    //alert_thread( pthread_getw32threadhandle_np( (thread_t)tid ) );
#endif 

    thread::join(tid);
    //pthread_join( (thread_t)tid, &p );
}



////////////////////////////////////////////////////////////////////////////////
void cxx_cleanup_invoker( void* )
{
#ifndef SYSTYPE_MSVC
    throw new thread::Exception();
#endif
}

////////////////////////////////////////////////////////////////////////////////
static void* _def_thread( void* p )
{
    bool waserr = false;
    thread_info* ti = (thread_info*)p;

    t_thread_fnc tfnc = ti->_fnc;
    void* targ = ti->_arg;

    bool critical = (ti->_flags & thread_info::fCRITICAL) != 0;
    opcd e = 0;

    try
    {
        targ = tfnc( targ );
    }
    catch( thread::Exception& )
    {
    }
    catch( opcd cd )
    {
        opcd e = cd;

        waserr = true;
        TreeMgr::Attribs at;
        opcd ne = SRVROOTA._objmgr.get_node_attribs( ti->_oid, at );

        SRVROOTA.post_server_msg( LOGMSG::TYPE_ALERT, 0 )
            << "Exception in working thread of object "
            << ti->_oid << " (class: " << at.nc.get_class_name()
            << ", name: " << at.name
            << ", thread name: " << ti->_name << ") - "
            << opcd_formatter(cd) << EOM;
    }
    catch(...)
    {
        e = ersEXCEPTION;

        waserr = true;
        TreeMgr::Attribs at;
        opcd ne = SRVROOTA._objmgr.get_node_attribs( ti->_oid, at );

        SRVROOTA.post_server_msg( LOGMSG::TYPE_ALERT, 0 )
            << "Exception in working thread of object "
            << ti->_oid << " (class: " << at.nc.get_class_name()
            << ", name: " << at.name
            << ", thread name: " << ti->_name << ")" << EOM;
    }

    //unhandled exception in the thread, destroy the object
    if( e && critical )
        SRVROOTA.add_to_dead_list( ti->_oid );

    SRVROOTA._objmgr.thread_unregister( ti->_oid, thread::self() );

    ti->_oid = UMAX32;
    return targ;
}

////////////////////////////////////////////////////////////////////////////////
opcd TreeMgr::spawn_thread( LNID n, t_thread_fnc start, void* arg, bool crit, const token& name )
{
    GUARDME;

    REF id;
    if( !_tree.get_node( n, id ) )
        return ersOUT_OF_RANGE "invalid index";

    if( id->_node->is_exit_signalled() )
        return ersUNAVAILABLE "object exiting";

    local<thread_info> ti = new thread_info;
    ti->_arg = arg;
    ti->_fnc = start;
    ti->_oid = n;
    ti->_name = name;
    ti->_tempid = n;
    ti->_flags = crit ? thread_info::fCRITICAL : 0;

    thread tid;
    if( thread::invalid() == tid.create( _def_thread, ti.ptr(), ti.ptr() ) )
        return ersFAILED;

    ti.eject();

    uint* p = _change_list.add(2);
    p[0] = tree_info::CHANGE_SET_THREAD | n;
    p[1] = (uint)tid;

    *id->_node->_thr_own.add() = tid;

    return 0;
}



} //namespace coid
